﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BCVP.Net8.Common.appsettings
{
    /// <summary>
    /// appsettings.json类
    /// </summary>
    public class AppSettings
    {
        public static IConfiguration Configuration { get; set; }

        public string contentPath { get; set; }


        public AppSettings(string contentPath)
        {
            string Path = "appsetting.json";

            // 如果你把配置文件 根据环境变量来分开了，可以这样写

            Configuration = new ConfigurationBuilder()
                .SetBasePath(contentPath)
                .Add(new JsonConfigurationSource
                {
                    Path = Path,
                    Optional = false,
                    ReloadOnChange = true
                }) // 这样的话可以字节读目录里的json文件,而不是bin文件夹下的，所以不用修改复制属性
                .Build();

        }


        public AppSettings(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        /// <summary>
        /// 封装要操作的字符
        /// </summary>
        /// <param name="section">节点配置</param>
        /// <returns></returns>
        public static string app(params string[] section)
        {
            try
            {
                if (section.Any())
                {
                    return Configuration[string.Join(":", section)];
                }
            }
            catch (Exception)
            {

                throw;
            }

            return "";
        }

        /// <summary>
        /// 递归获取配置信息数组
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="section"></param>
        /// <returns></returns>
        public static List<T> app<T>(params string[] section)
        {
            List<T> list = new List<T>();

            // 引用Microsoft.Extensions.Configuration.Binder包
            Configuration.Bind(string.Join(":", section), list);

            return list;
        }

        /// <summary>
        /// 根据路径 configuration["App.Name"]
        /// </summary>
        /// <param name="sectionsPath"></param>
        /// <returns></returns>
        public static string GetValue(string sectionsPath)
        {
            try
            {
                return Configuration[sectionsPath];
            }
            catch (Exception)
            {

            }

            return "";
        }
    }

}
